<template>
  <div class="box-padding">
    <Form label-position="top">
      <Header class="header-cont main__title--top">{{$route.params.name}}</Header>
    <Row>
      <Col span="24" class="role-twoCol">
      <FormItem label="角色类型" :required="$route.params.type == 'details' ? false : true">
        <Select
          v-model="roleObj.type"
          style="width:200px"
          :disabled="isDisabled || isUserType"
          @on-change='changeType'
        >
          <Option
            v-for="item in roleType"
            :value="item.code"
            :key="item.code"
            >{{ item.name }}</Option
          >
        </Select>
      </FormItem>
      </Col>
      <Col span="24" class="role-twoCol">
      <FormItem label="角色名称" :required="$route.params.type == 'details' ? false : true">
        <Input
          v-model="roleObj.name"
          clearable
          style="width: 200px"
          :disabled="isDisabled"
          placeholder="请输入角色名称"
        />
      </FormItem>
      </Col>
      <Col span="24" class="role-twoCol">
      <FormItem label="适用范围" :required="$route.params.type == 'details' ? false : true">
        <Select
          v-model="roleObj.scope"
          style="width:200px"
          :disabled="isDisabled || isUserArea"
        >
          <Option
            v-for="item in scopeList"
            :value="item.code"
            :key="item.code"
            >{{ item.name }}</Option
          >
        </Select>
      </FormItem>
      </Col>
    </Row>
    <div class="role-box">
      <span>角色授权</span>
      <Tabs value="menuList" @on-click="tabClick">
        <TabPane :label="item.name" name="menuList" v-for="(item,index) in roleTabArr" :key="index">
          <Tree
            :data="list"
            show-checkbox
            multiple
            :render="renderContent"
            ref="tree"
            @on-check-change="choiceData"
          ></Tree>
        </TabPane>
        <!-- <TabPane label="APP端" name="appList">
          <span>系统管理</span>
          <div class="role-div" v-for="(item, index) in list" :key="index">
            <span class="admin-role">{{ item.name }}</span>
            <CheckboxGroup
              v-model="appList[index]"
              @on-change="checkboxChange1(index)"
            >
              <Checkbox
                :label="ite.name"
                v-for="(ite, ind) in item.children"
                :key="ind"
                :disabled="isDisabled"
              ></Checkbox>
            </CheckboxGroup>
          </div>
        </TabPane>
        <TabPane label="小程序" name="miniprogramList">
          <span>系统管理</span>
          <div class="role-div" v-for="(item, index) in list" :key="index">
            <span class="admin-role">{{ item.name }}</span>
            <CheckboxGroup
              v-model="miniprogramList[index]"
              @on-change="checkboxChange2(index)"
            >
              <Checkbox
                :label="ite.name"
                v-for="(ite, ind) in item.children"
                :key="ind"
                :disabled="isDisabled"
              ></Checkbox>
            </CheckboxGroup>
          </div>
        </TabPane>
        <TabPane label="公众号" name="officialAccountsList">
          <span>系统管理</span>
          <div class="role-div" v-for="(item, index) in list" :key="index">
            <span class="admin-role">{{ item.name }}</span>
            <CheckboxGroup
              v-model="officialAccountsList[index]"
              @on-change="checkboxChange2(index)"
            >
              <Checkbox
                :label="ite.name"
                v-for="(ite, ind) in item.children"
                :key="ind"
                :disabled="isDisabled"
              ></Checkbox>
            </CheckboxGroup>
          </div>
        </TabPane> -->
      </Tabs>
    </div>
    <div class="role-bottom" v-show="$route.params.type != 'details'">
      <Button type="primary" @click="saveRole">保存</Button>
      <Button style="margin-left:20px;" @click="closetab">取消</Button>
    </div>
    </Form>

  </div>
</template>

<script>
import { mapMutations } from 'vuex'

export default {
  data() {
    return {
      list: [],
      roleObj: {},
      scopeList: [],
      roleType: [],
      scope: {},
      menuList: [],
      appList: [],
      miniprogramList: [],
      officialAccountsList: [],
      isDisabled: '',
      selectedPermissions: [],
      type: '',
      isUserType: false,
      isUserArea: false,
      userInfo: JSON.parse(localStorage.getItem('userList')),
      roleTabArr:[]
    }
  },
  mounted() {
    this.dictTypeCode()
    this.dictTypeCode1()
    this.roleTab()
    this.type = this.$route.params.type
    this.isDisabled = this.$route.params.type == 'details' ? true : false
    const flag = this.$route.params.type === 'add'
    if (flag) {
      this.roleBeforeAdd()
    } else {
      this.roleDetail()
    }
  },
  methods: {
    ...mapMutations(['closeTag']),
    // tree控件的render渲染
    renderContent(h, { root, node, data }) {
      return h(
        'span',
        {
          style: {
            display: 'inline-flex',
            width: '100%'
          }
        },
        [
          h('span', [h('span', data.title)]),
          h(
            'span',
            {
              style: {
                display: 'flex',
                float: 'right',
                marginLeft: '20px'
              }
            },
            (data.buttons || []).map(button => {
              return h(
                'Checkbox',
                {
                  props: {
                    value: button.selected,
                    disabled: this.$route.path.indexOf('details') > -1
                  },
                  on: {
                    'on-change': e => {
                      button.selected = e
                      const flag =
                        e || data.buttons.filter(b => b.selected).length > 0
                      this.$set(data, 'checked', flag)
                      this.$set(data, 'indeterminate', false)
                      this.$refs.tree[0].updateTreeUp(data.nodeKey)
                      this.$refs.tree[0].updateTreeDown(data, {
                        e,
                        indeterminate: false
                      })
                    }
                  }
                },
                button.name
              )
            })
          )
        ]
      )
    },
    // 编辑关闭
    closetab() {
      let self = this
      this.closeTag({
        name: self.$route.params.type == 'add' ? 'role-add' : self.$route.params.type == 'details' ? 'role-detail' : 'role-edit',
        params: { ...this.$route.params },
        query: {
          ...this.$route.query
        }
      })
      this.$router.push({ name: 'role-management' })
    },
    // 角色详情
    roleDetail() {
      if (this.$route.params.name === '日志详情') {
        this.$api.operationLog
          .getOperationLogDetail(this.$route.params.id)
          .then(res => {
            if (res.code === 200) {
              let data = JSON.parse(res.data.params)
              this.roleObj = { ...data }
              this.list = this.roleObj.menuList
              const preHandle = nodes => {
                nodes.forEach(n => {
                  this.$set(n, 'expand', true)
                  if (this.$route.params.type === 'details') {
                    this.$set(n, 'disabled', true)
                  }
                  if (n.buttons && n.buttons.length > 0) {
                    n.buttons.forEach(b => {
                      const flag =
                        b.selected ||
                        n.buttons.filter(bb => bb.selected).length > 0
                      this.$set(n, 'checked', flag)
                      this.$set(n, 'indeterminate', false)
                    })
                  }
                  if (n.children.length > 0) {
                    preHandle(n.children)
                  }
                })
              }
              preHandle(this.list)
            } else {
              this.$Message.error(res.message)
            }
          })
      } else {
        this.$api.roleManagement
          .roleDetail({
            id: this.$route.params.id
          })
          .then(resp => {
            if (resp.code == 200) {
              this.roleObj = resp.data
              this.list = resp.data.menuList
              const preHandle = nodes => {
                nodes.forEach(n => {
                  this.$set(n, 'expand', true)
                  if (this.$route.params.type === 'details') {
                    this.$set(n, 'disabled', true)
                  }
                  if (n.buttons && n.buttons.length > 0) {
                    n.buttons.forEach(b => {
                      const flag =
                        b.selected ||
                        n.buttons.filter(bb => bb.selected).length > 0
                      this.$set(n, 'checked', flag)
                      this.$set(n, 'indeterminate', false)
                    })
                  }
                  if (n.children.length > 0) {
                    preHandle(n.children)
                  }
                })
              }
              preHandle(this.list)
              //编辑页面：如果用户为集团用户，角色选专用角色，角色适用范围为公司级且不可再选
              if(resp.data.userInOrgType === 'ROOT_ENTERPRISE_USER' && resp.data.type === 'ROLE_TYPE_2'){
                this.isUserArea = true
              }
            }
          })
      }
    },
    // 适用范围
    dictTypeCode() {
      this.$api.roleManagement.dictTypeCode('RANGE_APPLICATION').then(resp => {
        if (resp.code == 200) {
          this.scopeList = resp.data
          switch (this.userInfo.userInOrgType) {
              case 'NOMAL_ENTERPRISE_USER': //机构级
                this.roleObj.scope = 'ENTERPRISE_LEVEL'
                this.isUserType = true
                break
              case 'PROJECT_TEAM_USER': //项目级
                this.roleObj.scope = 'PROJECT_LEVEL'
                this.isUserType = true
                break
              default:
                //其他
                this.isUserType = false
                break
            }
        }
      })
    },
    // 角色权限Tab
    roleTab() {
      this.$api.roleManagement.dictTypeCode('ROLE_AUTH').then(resp => {
        if (resp.code == 200) {
          this.roleTabArr = resp.data
        }
      })
    },
    changeType(value) {
      if (this.userInfo.userInOrgType == 'ROOT_ENTERPRISE_USER' && value == 'ROLE_TYPE_2') {
        //顶级是选择专用只有项目级
        this.isUserArea = true
        this.roleObj.scope = 'ENTERPRISE_LEVEL'
      } else {
        this.isUserArea = false
      }
    },
    // 角色类型
    dictTypeCode1() {
      this.$api.roleManagement.dictTypeCode('ROLE_TYPE').then(resp => {
        if (resp.code == 200) {
          this.roleType = resp.data
          if(this.userInfo.userInOrgType != 'ROOT_ENTERPRISE_USER' ){
              //不是顶级的话
              this.roleObj.type = "ROLE_TYPE_2"
              this.isUserArea = true
          }else{
            this.isUserArea = false
          }
        }
      })
    },
    // 角色授权
    roleBeforeAdd() {
      this.$api.roleManagement.roleBeforeAdd().then(resp => {
        if (resp.code == 200) {
          this.scope = resp.data
          resp.data.menuList.map(item => {
            item.children.map(b => {
              if (b.buttons && b.buttons.length > 0) {
                this.$set(b, 'selectedPermissions', [])
              }
            })
          })
          this.list = resp.data.menuList
        }
      })
    },
    // 角色切换
    tabClick(value) {
      if (value == 'menuList') {
        this.roleBeforeAdd()
        //this.list = this.scope.menuList
        console.log(this.list)
        this.list.forEach(a => {
          let a1 = []
          a.children.forEach(b => {
            if (b.selected) {
              a1.push(b.name)
            }
          })
          this.menuList.push(a1)
        })
      } else if (value == 'appList') {
        this.list = this.scope.appList
      } else if (value == 'miniprogramList') {
        this.list = this.scope.miniprogramList
      } else {
        this.list = this.scope.officialAccountsList
      }
    },
    choiceData(selectedList, current) {
      console.log(selectedList)
      console.log(current)
      const preHandle = node => {
        if (node.buttons.length > 0) {
          node.buttons.forEach(b => {
            b.selected = current.checked
          })
        }
        if (node.children && node.children.length > 0) {
          node.children.forEach(c => {
            preHandle(c)
          })
        }
      }
      preHandle(current)
      // console.log(this.list)
    },
    // 复选框监听
    checkboxChange(index) {
      this.menuList[index].forEach(a => {
        this.list[index].children.forEach(b => {
          if (a == b.name) {
            this.$set(b, 'selected', true)
          }
        })
      })
      this.roleObj.menuList = this.list
    },
    checkboxChange1(index) {
      this.appList[index].forEach(a => {
        this.list[index].children.forEach(b => {
          if (a == b.name) {
            this.$set(b, 'selected', true)
          }
        })
      })
      this.roleObj.appList = this.list
    },
    checkboxChange2(index) {
      this.miniprogramList[index].forEach(a => {
        this.list[index].children.forEach(b => {
          if (a == b.name) {
            this.$set(b, 'selected', true)
          }
        })
      })
      this.roleObj.miniprogramList = this.list
    },
    checkboxChange3(index) {
      this.officialAccountsList[index].forEach(a => {
        this.list[index].children.forEach(b => {
          if (a == b.name) {
            this.$set(b, 'selected', true)
          }
        })
      })
      this.roleObj.officialAccountsList = this.list
    },
    // 保存修改/新增
    saveRole() {
      // 校验
      if (!this.roleObj.type) {
        this.$Message.error('请选择角色类型')
        return
      }
      if (!this.roleObj.name) {
        this.$Message.error('请填写角色名称')
        return
      }
      if (this.roleObj.name.length > 20) {
        this.$Message.warning("角色名称不能超过20个字符！");
        return;
      }
      if (!this.roleObj.scope) {
        this.$Message.error('请选择适用范围')
        return
      }
      const preHandle = nodes => {
        nodes.forEach(n => {
          if (n.checked || n.indeterminate) {
            n.selected = true
          }else{
            n.selected = false
          }
          if (n.children && n.children.length > 0) {
            preHandle(n.children)
          }
        })
      }
      preHandle(this.list)
      this.roleObj.menuList = this.list
      if (this.$route.params.type == 'edit') {
        this.$api.roleManagement.editRole(this.roleObj).then(resp => {
          if (resp.code == 200) {
            this.$Message.success('修改成功')
            this.closetab()
          } else {
            this.$Message.warning(resp.message)
          }
        })
      } else {
        this.$api.roleManagement.addRole(this.roleObj).then(resp => {
          if (resp.code == 200) {
            this.$Message.success('添加成功')
            this.closetab()
          } else {
            this.$Message.warning(resp.message)
          }
        })
      }
    }
  }
}
</script>

<style scoped>
.role-title {
  color: #333;
  font-size: 20px;
  height: 50px;
  line-height: 50px;
  border-bottom: 1px solid #dcdee2;
  font-weight: bold;
  margin-bottom: 20px;
}

.role-oneCol {
  height: 50px;
  line-height: 50px;
  font-size: 14px;
}

.role-box {
  padding-top: 20px;
}

.role-div {
  display: flex;
  flex: column;
  padding-left: 50px;
  height: 40px;
  line-height: 40px;
}

.admin-role {
  padding-right: 30px;
  min-width: 100px;
}

.role-bottom {
  padding: 20px 0;
  display: flex;
  justify-content: center;
}
</style>
